import url, { prefix } from './url'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
// import { Message } from 'element-ui'

export const uploadConfig = () => {
  return {
    headers: {
      Authorization: getToken()
    },
    action: prefix + url.put,
    name: 'multipartFile'
  }
}

/**
 *  下载文件 直接通过连接 
 * @param fileUrl 文件地址 
 * 
 * 用这个的前提是不需要token或者后端提供了服务器地址
 */
export const downloadFileByUrl = fileUrl => {
  // const strs = fileUrl.split('/')
  // const fileName = strs[strs.length - 1]

  // const downloadUrl = prefix + url.download + fileName
  const downloadUrl = fileUrl
  let elemIF = document.getElementById('fileDownLoad')
  if (!elemIF) {
    elemIF = document.createElement('iframe')
    elemIF.id = 'fileDownLoad'
    elemIF.src = downloadUrl
    elemIF.style.display = 'none'
    document.body.appendChild(elemIF)
  } else {
    elemIF.src = ''
    elemIF.src = downloadUrl
  }
}

/**
 *  下载文件  通过接口请求到文件流再转换成文件
 * @param fileUrl  
 * @param fileName  
 * 
 * 可以带token
 */
export async function downloadFile({
  fileUrl,
  fileName
}) {
  // roleName,remark
//   const strs = fileUrl.split('/')
//   const fileName = strs[strs.length - 1]
 
  const response = await request({
    url: url.download + '/' + fileName,
    method: 'get',
    formatRes: false
  })

  const fileLink = window.URL.createObjectURL(new Blob([response.data]))
  const link = document.createElement('a')
  link.href = fileLink
  // link.setAttribute('download', fileName)
  link.download = fileName  
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}
